import { ref, onMounted, onUnmounted, watch } from 'vue';

// 设计稿尺寸（px）
const baseWidth = 1920;
const baseHeight = 1080;

// 需保持的比例
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));

export default function useScale() {
  // 缩放值
  const scale = ref({
    width: "1",
    height: "1",
  });

  // 定时函数
  const drawTiming = ref(null);

  // 引用元素
  const appRef = ref(null);
  
  const calcRate = () => {
    console.log("appRef",appRef.value);
    if (!appRef.value) return;
    console.log(2);
    // 当前宽高比
    const currentRate = parseFloat((document.body.clientWidth / document.body.clientHeight).toFixed(5));
    const NewWidth = 1920;
    const NewHeight = 1080;
    const scaleX = parseFloat((window.innerWidth / NewWidth).toFixed(5));
    const scaleY = parseFloat((window.innerHeight / NewHeight).toFixed(5));
    if (currentRate > baseProportion) {
      console.log("表示更宽");
      // 表示更宽
      scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5);
      scale.height = (window.innerHeight / baseHeight).toFixed(5);
      appRef.value.style.transform = `scale(${scaleX}, ${scaleY}) translate(-50%, -50%)`;
      appRef.value.style.overflow = "hidden";
      document.getElementsByTagName("body")[0].className = "hidOverflow";
    } else {
      console.log("表示更高");
      // 表示更高
      scale.width = (window.innerWidth / baseWidth).toFixed(5);
      scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5);
      appRef.value.style.transform = `scale(${scaleX}, ${scaleY}) translate(-50%, -50%)`;
      appRef.value.style.overflow = "hidden";
    }
  };

  const resize = () => {
    clearTimeout(drawTiming.value);
    drawTiming.value = setTimeout(() => {
      calcRate();
    }, 200);
  };

  onMounted(() => {
    resize()
    window.addEventListener("resize", resize);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", resize);
  });

  // watch(() => [window.innerWidth, window.innerHeight], () => {
  //   clearTimeout(drawTiming.value);
  //   drawTiming.value = setTimeout(() => {
  //     calcRate();
  //   }, 200);
  // });

  return {
    appRef,
    scale,
    resize,
  };
}